package com.ml4ai.backend.services.providers

import java.util

import com.google.gson.{Gson, GsonBuilder, JsonParser}
import com.ml4ai.backend.consts.UserConstants
import com.ml4ai.backend.services.{DbMapService, RabbitmqService}
import com.ml4ai.backend.services.capability._
import com.ml4ai.core.stack.elasticsearch.ElasticSearchAgent
import com.ml4ai.core.stack.mq.RabbitMQAgent
import javax.annotation.PostConstruct
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.{Autowired, Value}
import org.springframework.stereotype.Service

@Service
class PublicContentCommandReceiver extends CommandReceiver {

  @Value("${elasticsearch.servers}") private val esServers: String = null
  @Value("${elasticsearch.cluster}") private val cluster: String = null
  @Autowired var rabbitmqService:RabbitmqService = null
  private var elasticsearch: ElasticSearchAgent = null
  private var rabbitMQAgent: RabbitMQAgent = null
  private var googleJsonWrapperBean: Gson = null
  private var jsonParser: JsonParser = null
  @Autowired var dbMapService: DbMapService = null

  @PostConstruct def init(): Unit = {
    elasticsearch = ElasticSearchAgent.builder.esServers(esServers).esCluster(cluster).build
    rabbitMQAgent = rabbitmqService.getRabbitMQAgent
    jsonParser = new JsonParser
    val googleJsonWrapperBuilder = new GsonBuilder
    googleJsonWrapperBuilder.serializeNulls
    googleJsonWrapperBuilder.setDateFormat("yyyy-MM-dd")
    googleJsonWrapperBean = googleJsonWrapperBuilder.create
  }

  override def execute(command: Command): Unit = {
    val token = command.get("token")
    if (StringUtils.isNotEmpty(token)) {
      val tokenStoreMap = dbMapService.generateLocalMapWrapper(UserConstants.TOKEN_USER_MAP)
      val username = tokenStoreMap.get(token)
      val parameter = googleJsonWrapperBean.fromJson(command.get("parameter"), classOf[util.Map[String, AnyRef]])
      parameter.put("createUser", username)
      elasticsearch.getClient.prepareIndex("app-contents", "default").setSource(parameter).get
      val response = new java.util.HashMap[String, AnyRef]
      response.put("code", "200")
      response.put("msg", "发布成功")
      response.put("data", "")
      rabbitMQAgent.produceText("", command.getCallback, googleJsonWrapperBean.toJson(response), false)
    } else {
      val response = new java.util.HashMap[String, AnyRef]
      response.put("code", "500")
      response.put("msg", "发布失败，没有登录")
      response.put("data", "")
      rabbitMQAgent.produceText("", command.getCallback, googleJsonWrapperBean.toJson(response), false)
    }
  }

  override def getSupport(): String = "publicContent"
}
